package com.octopus.algorithm;

import java.util.ArrayList;

import com.octopus.string.StringUtils;

public class BasicDigit {
	public static void reverseCharArray(char[] charArray) {
		if (charArray == null || charArray.length == 0) {
			return;
		} else {
			int loopCount = charArray.length / 2;
			for (int i = 0; i < loopCount; i++) {
				char tempValue = charArray[i];
				charArray[i] = charArray[charArray.length - 1 - i];
				charArray[charArray.length - 1 - i] = tempValue;
			}
		}
	}

	public static int[] decToSpecDigitIntArrayPosOnly(long number, int specDigit)
			throws UnSupportZeroOrNegativeDigit {
		int[] result = null;
		number = Math.abs(number);
		if (specDigit <= 1) {
			throw new UnSupportZeroOrNegativeDigit(specDigit);
		}
		ArrayList<Long> modSequence = new ArrayList<Long>();
		ArrayList<Long> divSequence = new ArrayList<Long>();
		long div = 0;
		long mod = 0;
		do {
			div = number / specDigit;
			mod = number % specDigit;
			divSequence.add(div);
			modSequence.add(mod);
			number = div;
		} while (div >= specDigit);

		if (div != 0) {
			modSequence.add(div);
		}
		result = new int[modSequence.size()];
		for (int index = 0, size = modSequence.size(); index < size; index++) {
			long digit = modSequence.get(index);
			result[index] = (int) digit;
		}
		return result;
	}

	public static long specDigitIntArrayToDecPosOnly(int[] intArray,
			int specDigit) throws UnSupportZeroOrNegativeDigit {
		if (specDigit <= 0) {
			throw new UnSupportZeroOrNegativeDigit(specDigit);
		}
		long result = 0;
		if (intArray == null) {
			return result;
		}
		for (int i = 0, size = intArray.length; i < size; i++) {
			if (intArray[i] == 0) {
				continue;
			}
			result += intArray[i] * (intPowerAbsTimes(specDigit, i));
		}
		return result;
	}

	public static long intPowerAbsTimes(int value, int times) {
		long result = 1;
		times = Math.abs(times);
		for (int i = 0; i < times; i++) {
			result *= value;
		}
		return result;

	}

	public static class UnSupportZeroOrNegativeDigit extends Exception {
		
		private static final long serialVersionUID = 1L;
		private int digit;

		public UnSupportZeroOrNegativeDigit(int digit) {
			this.digit = digit;
		}

		public String toString() {
			return StringUtils.concat("Unsupport zero or negative number:",
					String.valueOf(digit));
		}
	}
}
